package com.sbs.demo.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class CmdUtil {

    @Data
    public static class CmdOutput {
        private String output;
        private String error;
        private Integer result;
        private String cmd;
    }

    public static CmdOutput execCmd(String cmd) throws IOException, InterruptedException {
        log.info("执行命令：{}", cmd);
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new BufferedInputStream(process.getErrorStream())));
        StringBuilder logOutput = new StringBuilder();
        StringBuilder errorOutput = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("[cmd console] {}", line);
            errorOutput.append(line).append("\n");
        }
        BufferedReader br1 = new BufferedReader(new InputStreamReader(
                new BufferedInputStream(process.getInputStream())));
        while ((line = br1.readLine()) != null) {
            log.debug("[cmd console] {}", line);
            logOutput.append(line).append("\n");
        }
        int res = process.waitFor();
        log.info("cmd result:{}", res);
        br.close();
        br1.close();
        CmdOutput output = new CmdOutput();
        output.setError(errorOutput.toString());
        output.setOutput(logOutput.toString());
        output.setResult(res);
        output.setCmd(cmd);
        return output;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        String cmd = "ffmpeg -i D:\\test\\1.mp4 -filter_complex \"[0:v]split=2[base][key];[key]crop=100:100:0:0,geq=lum='alpha':a='(W-x)*(H-y)/WH'[ckout];[base][ckout]overlay=0:0\" -c:a copy D:\\test\\output.mp4";
        execCmd(cmd);
    }
}
